package com.ae.putingotdown.block;

import com.ae.putingotdown.Config;
import com.ae.putingotdown.cap.SingleItemStackHandler;
import net.minecraft.block.BlockState;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SUpdateTileEntityPacket;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Direction;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public class TilePlacedItem extends TileEntity {
    public SingleItemStackHandler handler;
    private int color = 0xffffff;
    private final LazyOptional<IItemHandler> lazyOptional = LazyOptional.of(() -> handler);

    public TilePlacedItem() {
        this(ItemStack.EMPTY, Config.MAX_COUNT.get());
    }

    public TilePlacedItem(ItemStack stack, int count) {
        super(Register.TILE_PLACED_INGOT.get());
        handler = new SingleItemStackHandler(stack, count, this);
    }

    @Nonnull
    @Override
    public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) {
        if (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {
            return lazyOptional.cast();
        }
        return super.getCapability(cap, side);
    }

    @Override
    public CompoundNBT save(CompoundNBT compoundNBT) {
        CompoundNBT nbt = super.save(compoundNBT);
        nbt.put("Inventory", handler.serializeNBT());
        nbt.putInt("Color", color);
        return nbt;
    }

    @Override
    public void load(BlockState state, CompoundNBT compoundNBT) {
        super.load(state, compoundNBT);
        handler.deserializeNBT(compoundNBT.getCompound("Inventory"));
        color = compoundNBT.getInt("Color");
    }

    @Override
    public void handleUpdateTag(BlockState state, CompoundNBT tag) {
        super.handleUpdateTag(state, tag);
        load(state, tag);
    }

    @Override
    public CompoundNBT getUpdateTag() {
        return save(new CompoundNBT());
    }

    @Override
    public void onDataPacket(NetworkManager net, SUpdateTileEntityPacket pkt) {
        load(level.getBlockState(pkt.getPos()), pkt.getTag());
    }

    @Nullable
    @Override
    public SUpdateTileEntityPacket getUpdatePacket() {
        return new SUpdateTileEntityPacket(getBlockPos(), 1, save(new CompoundNBT()));
    }

    public int getColor() {
        return color;
    }

    public void setColor(int color) {
        this.color = color;
    }
}
